<template>
	<view class="map-collect" >
		<view class="collect-top-news">
			<input type="text" v-model="keyword" placeholder="请输入关键词" />
			<view class="selete-city flex" @click="openPicker">
				<!-- <picker class="pier" @change="bindPickerChange" :range="piers" range-key="name"> -->
					<view class="selete-operator">{{ city }}</view>
				<!-- </picker> -->
				<view class="nabla"></view>
			</view>
			
			<view class="selete-county flex" @click="openPicker">
				<!-- <picker class="pier" @change="bindPickerChangeCounty" :range="countys" range-key="name"> -->
					<view class="selete-operator">{{ county }}</view>
				<!-- </picker> -->
				<view class="nabla"></view>
			</view>
		</view>
		<view class="news-done">
			<view class="news-done-left">
				<image src="/static/images/map-icon.png" mode=""></image>
				<switch :checked="switchChecked" @change="swit" />
			</view>
			<view class="news-done-right">
				<text class="have-check">{{ addData.length }}</text>
				<text class="partition">/</text>
				<text class="all">{{ searchNum }}</text>
			</view>
		</view>
		<view class="map-box">
			<!-- 腾讯地图采集 -->
			<view 
				class="" 
				:class="mapShow ? 'graduallyhidden' : 'graduallyshow' ">
				<view class="map graduallyshow">
					<web-view :src="src" style="height: 68vh;margin-top: 220rpx;"></web-view>
				</view>
			</view>
		</view>
		<view class="start-collecting" @click="startCollecting">
			{{ canStop ? '停止采集' : '开始采集' }}
		</view>
		<lotus-address 
			@choseVal="choseValue" 
			:lotusAddressData="lotusAddressData"
		></lotus-address>
		<hint v-if="hintVisitable" :hintTitle="hintTitle" />
	</view>
</template>

<script>
	import Vue from 'vue'
	import {VueJsonp} from 'vue-jsonp'
	Vue.use(VueJsonp)
	const vm = new Vue
	import lotusAddress from "@/components/Winglau14-lotusAddress/Winglau14-lotusAddress.vue";
	import hint from "@/components/index/hint.vue";
	//地图采集
	export default {
		name: 'mapCollect',
		data() {
			
			return {
				winHeight: 500,
				src: '',
				keyword: '',  //输入的关键词
				piers: [
					{
						name: '济南'
					},{
						name: '北京'
					},
				],
				countys: [
					{
						name: '天桥区'
					},{
						name: '市中区'
					},{
						name: '槐荫区'
					},
				],
				county: '选择区县',
				city: '选择城市',
				
				zoom:18,//地图相关设置
				center:{lng:0,lat:0},
				wHeight: '',
				switchChecked: true,  //控制地图显示  switch
				mapShow: false, //地图显示
				latitude: 39.91799,
				longitude: 116.397027,
				covers: [], //标记点地图数据
				map: {},
				lotusAddressData:{
					visible:false,
					provinceName:'',
					cityName:'',
					townName:'',
				},
				region:'',
				mapView: true, //地图视图 显示
				datas: [],
				hintTitle: '',  //底部提示的信息
				setIntervalTime: '', //循环定时器 几秒一个地址电话
				searchNum: 0,  //搜索出来的总数目,
				searchIn: 0, //当前搜索的条数 
				pageIndex: 1,  //查询的页数
				addData: [],  //搜索的数据
				canStop: false,  //是否显示停止采集的按钮  true显示
				hintVisitable: false,  //是否显示底部门店和电话信息
			}
		},
		components: {
			// BaiduMap,
			"lotus-address":lotusAddress,
			hint
		},
		onLoad() {
			this.wHeight = this.$store.state.ContentHeight-44;
			this.init();
			this.src = '/static/html/baidumap.html',
			uni.setStorageSync('storage_key','hello');
			console.log(uni.getStorageSync(
				'storage_key'
			),'kk')
		},
		onReady() {
			// this.map = uni.createMapContext("map", this);
			// console.log(this.map, ":this.map")
		},
		watch: {},
		methods: {
			//打开picker
			openPicker() {
				this.lotusAddressData.visible = true;
				this.lotusAddressData.provinceName = '北京';
				this.lotusAddressData.cityName = '北京市';
				this.lotusAddressData.townName = '东城区';
			},
			//回传已选的省市区的值
			choseValue(res){    
				//res数据源包括已选省市区与省市区code
				this.city = res.city;
				this.county = res.town;
				this.lotusAddressData.visible = res.visible;//visible为显示与关闭组件标识true显示false隐藏
				//res.isChose = 1省市区已选 res.isChose = 0;未选
				if(res.isChose){
					this.lotusAddressData.provinceName = res.province;//省
					this.lotusAddressData.cityName = res.city;//市
					this.lotusAddressData.townName = res.town;//区
					this.region = `${res.province} ${res.city} ${res.town}`; //region为已选的省市区的值
				}
			},
			
			////**************
			
			init() {
				let that = this;
				//发起网络请求获取数据
				//用uni.request(OBJECT)方法
				//我这里模拟下数据
				var data = [{
					id: 1,
					name: '雷军',
					imgUrl:'/static/images/location.png',
					lat: "36.675232",
					lng: "117.025711"
				}];
				that.MapData(that,data)
			},
			//地图数据初始化
			MapData(that, data) {
				let arrayData = [];
				for (var i = 0; i < data.length; i++) {
					arrayData.push({
						id: data[i].id, //marker点击事件回调会返回此id。建议为每个marker设置上Number类型id，保证更新marker时有更好的性能。
						latitude: data[i].lat, //纬度
						longitude: data[i].lng, //经度
						title: data[i].name, //点击时显示，callout存在时将被忽略
						iconPath:data[i].imgUrl, //项目目录下的图片路径，支持相对路径写法，以'/'开头则表示相对小程序根目录；也支持临时路径
						width: 32,
						height: 35,
						callout: {
							//自定义标记点上方的气泡窗口
							content: data[i].name,
							color: '', //文本颜色
							fontSize: 16, //文字大小
							borderRadius: 20, //callout边框圆角
							bgColor: '', //背景色
							padding: 6, //文本边缘留白
							display: 'BYCLICK', //'BYCLICK':点击显示; 'ALWAYS':常显
							textAlign: 'left', //文本对齐方式。有效值: left, right, center
						},
						label: {
							//为标记点旁边增加标签
							content: '', //标记点旁边的文字
							color: '#ff6600', //文本颜色
							fontSize: 16, //文字大小
							x: 0, //label的坐标，原点是 marker 对应的经纬度
							y: 0, //label的坐标，原点是 marker 对应的经纬度
							borderWidth: 1, //边框宽度
							borderColor: '', //边框颜色
							borderRadius: 10, //边框圆角
							bgColor: 'red',
							padding: 6, //	文本边缘留白
							textAlign: 'left', //文本对齐方式。有效值: left, right, center
						},
						anchor: {
							//经纬度在标注图标的锚点，默认底边中点 {x, y}，x表示横向(0-1)，y表示竖向(0-1)。{x: .5, y: 1} 表示底边中点
							x: .5,
							y: 1
						}
					});
				}
				//重新给地图数据赋值covers 
				that.covers = arrayData;
				// this.longitude = arrayData.longitude;
				// this.latitude= arrayData.latitude;
			},
			//地图点击事件
			markertap(e) {
				console.log("===你点击了标记点===")
				console.log("你点击的标记点ID是:" + e.detail.markerId)
				//console.log(e)
			},
			//点击地图时触发; App-nuve、微信小程序2.9支持返回经纬度
			tap(e){
				console.log("===你点击了地图点===")
				console.log(e) 
			},
			//在地图渲染更新完成时触发
			updated(e){
				console.log("===在地图渲染更新完成时触发===")
				console.log(e) 
			},
			// 点击 显示隐藏地图
			swit(e) {
				if (!e.target.value) !this.mapShow
				this.mapShow = !this.mapShow
			},
			//开始采集
			startCollecting() {
				if(this.canStop) {
					console.log(this.setIntervalTime,"this.setIntervalTime")
					clearInterval(this.setIntervalTime);
					this.setIntervalTime = null;
					this.canStop = !this.canStop;
				}else {
					uni.showLoading({title: '加载中',mask:true});
					this.canStop = !this.canStop;
					this.pageIndex = 1;
					let region = this.city;
					let keyword = this.keyword;
					if(region == '选择城市' || region == '') {
						return;
					}else {
						
						const params = {
							links: `https://api.map.baidu.com/place/v2/search?query=${keyword}&region=${region}${this.county}&output=json&ak=${this.config.baiduAk}&scope=2&page_num=0&page_size=20`,
							// links: `https://apis.map.qq.com/ws/place/v1/search?boundary=region(${region}${this.county},0)&keyword=${keyword}&key=${this.config.tengxunAk}&page_size=20&page_index=${this.pageIndex}`,
						}
						this.$post(this.api.getcurls, params).then((res) => {
							
							this.mapView = false;		//地图视图隐藏
							// 处理数据（地图中心店切换 底部信息显示）
							if(this.addData.length < res.count) {
								this.dospe(res)
							}
						}).catch((err) => {
							console.log(err)
						})
					}
				}
				
			},
			// 处理数据
			dospe(res) {
				this.searchNum = res.total;
				let i = 0;	
				this.setIntervalTime = setInterval(() => {
					if( this.addData.length < res.total ) {
						let item = res.data[i];
						let that = this;
						uni.hideLoading()
						that.hintTitle = item.name + item.detail_info.telephone;
						this.hintVisitable = true;
						that.datas = [{
							id: this.addData.length,
							name: res.data[i].title,
							imgUrl: '/static/images/location.png',
							lat: res.data[i].location.lat,
							lng: res.data[i].location.lng,
						}];
						//地图视图 显示
						this.mapView = true;
						//重新渲染视图 定位中心点
						that.MapData(that, that.datas)
						this.latitude = res.data[i].location.lat;
						this.longitude = res.data[i].location.lng;
						i++; 
						// 搜索到的数据添加到新地数组
						this.addData.push(res);
						if (i == res.data.length ) { //因为i++的原因，所以当i的值大于数组的长度-1的时候，清除定时器
							//当查询完一条（20）  后继续查询
							// 当新数组的数据数量小于请求来的总数量
							if(this.addData.length < res.count) {
								this.pageIndex++; //第二页
								this.startCollecting()
								
							}else{
								clearInterval(this.setIntervalTime);
								this.setIntervalTime = null;
							}
						}
					}else{
						// 判断当存储数据的数组的长度大于等于 请求来的数据总和时 清除定时器
						clearInterval(this.setIntervalTime);
						this.setIntervalTime = null;
					}
				},2000)
			},
		},
		onUnload:function(){  
		    if(this.setIntervalTime) {  
		        clearInterval(this.setIntervalTime);  
		        this.setIntervalTime = null;  
		    }  
		}
	}
</script>

<style lang="less" scoped>
	.flex{
		display: flex;
		align-items: center;
		.selete-operator{
			font-size: 34rpx;
			color: #999999;
			white-space: nowrap;
		}
	}
	.map-collect{
		.collect-top-news{
			.flex;
			padding: 30rpx 40rpx;
			.nabla{
				width: 0;
				height: 0;
				margin-left: 10rpx;
				border-right: 8px solid transparent;
				border-left: 8px solid transparent;
				border-top: 8px solid #A9A9A9;
				border-radius: 5px;
				
			}
			.selete-city{
				.flex;
				.pier{}
				
			}
			.selete-county{
				margin-left: 40rpx;
			}
		}
		.news-done{
			width: 100%;
			background: #DDDDDD;
			padding: 20rpx 48rpx;
			.flex;
			justify-content: space-between;
			box-sizing: border-box;
			.news-done-left{
				.flex;
				image{
					width: 80rpx;
					height: 80rpx;
					margin-right: 30rpx;
				}
			}
			.news-done-right{
				text{
					font-size: 40rpx;
				}
				.have-check{
					color: #39C1D7;
				}
				.partition{
					color: #999999;
					margin: 0 15rpx;
				}
				.all {
					color: #0F9487;
				}
			}
		}
		.map-box{
			.map-contain{
				height: 73vh;
			}
			.graduallyhidden{
				opacity: 0;
				transition: ease-in 0.3s; 
			}
			.graduallyshow{
				height: calc(100vh - 344rpx);
				opacity: 1;
				transition: ease-in 0.3s; 
			}
		}
		.start-collecting{
			width: 100%;
			height: 120rpx;
			line-height: 120rpx;
			position: fixed;
			bottom: 0;
			background: #5696F8;
			color: #ffffff;
			font-size: 32rpx;
			text-align: center;
			letter-spacing: 2px;
		}
	}
</style>
